from splinter.browser import Browser
from time import sleep



class Buy_Tickets(object):
    # 定义实例属性，初始化
    def __init__(self, username, passwd, order, passengers, dtime, starts, ends):
        self.username = username  # 用户名
        self.passwd = passwd  # 用户密码


        # 车次，0代表所有车次，依次从上到下，1代表所有车次，依次类推
        self.order = order


        # 乘客名
        self.passengers = passengers


        # 起始地
        self.starts = starts


        # 目的地
        self.ends = ends
        # 日期
        self.dtime = dtime
        # self.xb = xb
        # self.pz = pz
        self.login_url = 'https://kyfw.12306.cn/otn/login/init'
        self.initMy_url = 'https://kyfw.12306.cn/otn/index/initMy12306'
        self.ticket_url = 'https://kyfw.12306.cn/otn/leftTicket/init'
        self.driver_name = 'chrome'
        self.executable_path = 'C:\Python36\Scripts\chromedriver.exe'


    # 登录功能实现
    def login(self):
        self.driver.visit(self.login_url)
        self.driver.fill('loginUserDTO.user_name', self.username)
        self.driver.fill('userDTO.password', self.passwd)
        print('请输入验证码...')
        while True:
            if self.driver.url != self.initMy_url:
                sleep(1)
            else:
                break


    # 购票功能实现
    def start_buy(self):
        self.driver = Browser(driver_name=self.driver_name, executable_path=self.executable_path)
        self.driver.driver.set_window_size(700, 700)
        self.login()
        self.driver.visit(self.ticket_url)
        try:
            print('开始购票......')
            self.driver.cookies.add({"_jc_save_fromStation": self.starts})
            self.driver.cookies.add({"_jc_save_toStation": self.ends})
            self.driver.cookies.add({"_jc_save_fromDate": self.dtime})
            self.driver.reload()
            count = 0
            if self.order != 0:
                while self.driver.url == self.ticket_url:
                    self.driver.find_by_text('查询').click()
                    count += 1
                    print('第%d次点击查询......' % count)
                    try:
                        self.driver.find_by_text('预订')[self.order - 1].click()
                        sleep(1.5)
                    except Exception as ret:
                        print(ret)
                        print('预订失败......')
                        continue
            else:
                while self.driver.url == self.ticket_url:
                    self.driver.find_by_text('查询').click()
                    count += 1
                    print('第%d次点击查询......' % count)
                    try:
                        for i in self.driver.find_by_text('预订'):
                            i.click()
                            sleep(1)
                    except Exception as ret:
                        print(ret)
                        print('预订失败......')
                        continue
            print('开始预订......')
            sleep(1)
            print('开始选择用户......')
            for p in self.passengers:
                self.driver.find_by_text(p).last.click()
                sleep(0.5)
                if p[-1] == ')':
                    self.driver.find_by_id('dialog_xsertcj_ok').click()
            print('提交订单......')
            self.driver.find_by_id('submitOrder_id').click()
            sleep(2)
            print('确认选座......')
            self.driver.find_by_id('qr_submit_id').click()
            print('预订成功......')
        except Exception as ret:
            print(ret)




if __name__ == '__main__':
    # 用户名
    username = '12306用户名'
    # 密码
    password = '12306密码'
    # 车次选择，0代表所有车次
    order = 2


    # 乘客名，比如passengers = ['小明']
    passengers = ['']


    # 日期，格式为：'2018-05-10'
    dtime = '2018-05-10'


    # 出发地(需填写cookie值)，cookie值可以从浏览器里面找
    starts = '%u6DF1%u5733%2CSZQ'  # 深圳


    # 目的地(需填写cookie值)
    ends = '%u5317%u4EAC%2CBJP'  # 北京


    # xb =['硬座票']
    # pz=['成人票']
    buy1 = Buy_Tickets(username, password, order, passengers, dtime, starts, ends)
    buy1.start_buy()